package cn.ezios.huo.s3.old.file;

import cn.ezios.huo.common.mvc.Ret;
import cn.ezios.huo.s3.dao.SysStorageFile;
import cn.ezios.huo.s3.old.StorageClient;
import cn.ezios.huo.s3.dao.service.SysStorageFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FileService {
    private final StorageClient client;
    private final SysStorageFileService storageFileService;

    @Value("${s3.bucket-name}")
    private String bucket;

    public Ret avatarUpload(S3StorageDTO dto) {
        log.info("头像上传");
        SysStorageFile saved = saveDtoToDb(dto, "avatar");
        return saved == null ? Ret.error() : Ret.ok(saved);
    }

    /**
     * 获取直链
     * @param id
     * @return
     */
    public Ret getStraightChain(String id) {
        SysStorageFile fileObject = storageFileService.getById(id);
        if (fileObject == null) {
            return Ret.error();
        }
        String chain = fileObject.getBucket() + "/" + fileObject.getFileKey() + "/" +fileObject.getFileName();
        return Ret.ok(chain);
    }

    /**
     * 批量获取直链
     * @param ids
     * @return
     */
    public Ret listStraightChain(List<String> ids){
        List<SysStorageFile> list = storageFileService.lambdaQuery()
                .in(SysStorageFile::getId, ids)
                .list();
        if(list.isEmpty()){
            return Ret.error();
        }
        List<HashMap<String, String>> chains = list.stream().map(item -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("url", bucket + "/" + item.getFileKey() + "/" + item.getFileName());
            return map;
        }).toList();
        return Ret.ok(chains);
    }

    private SysStorageFile saveDtoToDb(S3StorageDTO dto, String dir) {
        dto.setDir(dir);
        dto.setBucket(bucket);
        client.upload(dto);
        SysStorageFile saved = save(dto);
        return saved;
    }

    private SysStorageFile save(S3StorageDTO dto) {
        log.info("保存文件");
        SysStorageFile storageFile = SysStorageFile.builder()
                .fileKey(dto.getDir())
                .bucket(dto.getBucket())
                .contentType(null)
                .fileName(dto.getFileName())
                .build();
        return storageFileService.save(storageFile) ? storageFile : null;
    }

    public static void main(String[] args) {
        new FileService(null, null);
    }


}
